#include "message.h"

#include <QJsonObject>
#include <QJsonDocument>

//Message::Message(QObject *parent)
//    : QObject{parent}
//{
//    m_timestamp = QDateTime::currentDateTime();
//}

Message::Message()
{
    m_type = SINGAL_CHAT;
    m_fromId = "";
    m_toId = "";
    m_timestamp = QDateTime::currentDateTime();

    m_groupId = "";
}

QString Message::getMessage(QString type,QString fromId, QString toId, QString data)
{
    QJsonObject jsonObj;
    jsonObj.insert("fromId", fromId);
    jsonObj.insert("toId", toId);
    jsonObj.insert("data", data);
    jsonObj.insert("timestamp", QDateTime::currentDateTime().toString("yyyy-M-dd hh:mm:ss"));
    QJsonDocument jsonDocument;
    jsonDocument.setObject(jsonObj);
    return QString(jsonDocument.toJson());
}

QString Message::getMessage()
{
//    getMessage("", m_fromId, m_toId, m_data);
    QJsonObject jsonObj;
    jsonObj.insert("type", getTypeString());
    jsonObj.insert("fromId", m_fromId);

    if (m_type == SINGAL_CHAT || m_type == FRIEND_REQUEST) {
        jsonObj.insert("toId", m_toId);
    } else if (m_type == GROUP_CHAT) {
        jsonObj.insert("groupId", m_groupId);
    }

    jsonObj.insert("data", m_data);
    jsonObj.insert("timestamp", m_timestamp.toString("yyyy-M-dd hh:mm:ss"));
    QJsonDocument jsonDocument;
    jsonDocument.setObject(jsonObj);

    return QString(jsonDocument.toJson());
}

QString Message::fromId() const
{
    return m_fromId;
}

void Message::setFromId(const QString &newFromId)
{
    m_fromId = newFromId;
}

QString Message::toId() const
{
    return m_toId;
}

void Message::setToId(const QString &newToId)
{
    m_toId = newToId;
}

QString Message::data() const
{
    return m_data;
}

void Message::setData(const QString &newData)
{
    m_data = newData;
}

QDateTime Message::timestamp() const
{
    return m_timestamp;
}

Message::Type Message::type() const
{
    return m_type;
}

QString Message::getTypeString() const
{
    switch (m_type) {
    case Message::SINGAL_CHAT:
        return "single_chat";
        break;
    case Message::GROUP_CHAT:
        return "group_chat";
        break;
    case Message::FRIEND_REQUEST:
        return "friend_request";
        break;
    default:
        break;
    }
}

void Message::setType(const QString &newType)
{
    if (newType.compare("single_chat") == 0 ) {
        m_type = SINGAL_CHAT;
    } else if (newType.compare("group_chat") == 0) {
        m_type = GROUP_CHAT;
    } else if (newType.compare("friend_request") == 0) {
        m_type = FRIEND_REQUEST;
    } else {
        qDebug() << __FILE__ << __LINE__ << __FUNCTION__ << "error";
    }
}

void Message::setType(Type type) {
    m_type = type;
}

QString Message::groupId() const
{
    return m_groupId;
}

void Message::setGroupId(const QString &newGroupId)
{
    m_groupId = newGroupId;
}

void Message::setTimestamp(const QDateTime &newTimestamp)
{
    m_timestamp = newTimestamp;
}
